<template>
  <div class="detail-module">
    <div class="left">
      <div class="scholl-name">
        <img
          class="img"
          src="@/assets/user.png"
        />
        <div class="c">
          <div class="name">{{ classRoom.companyEntity.company }}</div>
          <div class="num" >{{userType==4?'学生账号':'老师账号'}}{{classRoom.userInfo.account}}</div>
        </div>
      </div>
      <div class="white-module chapter">
        <div class="title">
          <div class="name"><span class="line"></span> 课堂章节</div>
          <div class="quit-btn" @click="signOutClassRoom">退出课堂</div>
        </div>
        <div class="course">
          <div class="name">
            <img src="@/assets/common/active_learn.png" />
            {{ classRoom.courseEntity ? classRoom.courseEntity.title : '' }}
          </div>
          <img v-if="studyType==3" src="@/assets/common/icon_grey_triangle.png" />
        </div>
        <div class="data global-scroll">
          <div
            class="item"
            :class="index == classHourIndex ? 'active' : ''"
            v-for="(item, index) in classRoom.classHourList"
            :key="index"
            @click="changeClassHour(index,item.id)"
            style="cursor:pointer"
          >
            <span>第{{ item.orderNum }}课时</span>
            {{ item.title }}
          </div>
        </div>
      </div>
      <div v-if="studyType==3" class="white-module student-list">
        <div class="title">
          <div class="name">
            <span class="line"></span>
            在线学生<div class="num">{{classRoom.onlineNum}}<span></span></div>
          </div>
          <div class="enlarge">
            <img src="@/assets/classroom/enlarge.png" />
          </div>
        </div>
        <div class="evaluate">
          <div class="text-line">
            <div class="text">完成评价 {{ classRoom.completedQuestion }}/<span>{{classRoom.onlineStudent.length}}</span></div>
            <div class="line">
              <span :style="{width: (1*100/classRoom.onlineStudent.length)+'%'}"></span>
            </div>
          </div>
<!--          <div class="excel">导出全部</div>-->
        </div>
        <div class="data global-scroll">
          <div
            class="item"
            :class="item.onlineFlag == false ? 'item-no' : ''"
            :key="index"
            v-for="(item, index) in classRoom.onlineStudent"
          >
            <div class="number"><span></span>{{item.username}}</div>
            <div class="status" v-if="item.questionStatus != 0 && item.answerNum > 0">完成</div>
            <div class="status" v-else>未完成</div>
            <!--学生只能评价自己，不能查看别人-->
            <div class="btn" v-if="userType==4">
              <el-button type="text" v-if="item.userId == userInfo.id" @click="showAssesment(item)">评价</el-button>
              <div class="status" v-else>--</div>
            </div>
            <div class="btn" v-else>
              <el-button type="text" @click="showAssesment(item)" v-if="item.questionStatus != 0 && item.answerNum > 0">查看</el-button>
              <div class="status" v-else>--</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="right">
      <!--1 评价-->
      <TeacherEvaluation  :ref="setItemRef" v-if="studyType == 1"  :classRoom="classRoom" :hour-id="classRoom.hourId" :class-room-id="classRoom.classRoomId"></TeacherEvaluation>
      <!--2 标准学习台-->
	    <StudyDesk v-else-if="studyType == 2" :classRoom="classRoom"></StudyDesk>
      <!--3 课堂学习台-->
      <course v-else  :classRoom="classRoom" :classHourIndex="classHourIndex"></course>
    </div>

    <!--课堂评价-->
    <el-dialog title="课堂评价" v-model="classRoom.assessment" width="700px">
      <div style="" class="student">
        <div
          style="
            margin-bottom: 5px;
            border-radius: 5px;
            height: 450px;
            padding: 0 15px;
            overflow-y: scroll;
          "
        >
          <div class="grading global-scroll">
            <div  class="item" v-for="(item, index) in topicArray.questionList" :key="index">
              <el-row  style="margin-top: 10px;">
                <el-col :span="0.5">
                  <div class="title row" rows="3" style="display: inline">
                    <span>{{ index + 1 }}.</span>
                  </div>
                </el-col>
                <el-col :span="16"  >
                  <div class="title"> {{item.title}} （<span>
                    {{ item.type===1?'填空题': item.type===2?'单选题':item.type===3?'多选题':item.type===4?'评分题':'简答题'}}
                  </span>）</div>
                </el-col>
              </el-row>

              <div class="answer-module" style="padding-left: 10px;">
                <div v-if="item.type == 1" class="input">
                  <el-input type="text" placeholder="请填写答案" v-model="item.answer"></el-input>
                </div>
                <div v-if="item.type == 2" class="radio">
                  <el-radio-group class="" v-model="item.answer" disabled>
                    <div>
                      <div v-for="(e, num) in item.options" :key="num">
                        <el-radio :label="e.value">
                          <span >{{e.option}}</span>
                        </el-radio>
                      </div>
                    </div>
                  </el-radio-group>
                </div>
                <div v-if="item.type == 3" class="checkbox">
                  <el-checkbox-group v-model="item.answers">
                    <div>
                      <div v-for="(e, num) in item.options" :key="num">
                        <el-row>
                          <el-col :span="16" style="display: inline">
                            <el-checkbox v-model="e.result" :label="e.option" :key="e.option" disabled>
                              <span>{{e.option}}</span>
                            </el-checkbox>
                          </el-col>
                        </el-row>
                      </div>
                    </div>
                  </el-checkbox-group>
                </div>
                <div v-if="item.type == 4" class="five">
                  <el-rate
                      v-model="item.answer"
                      :colors="'#01a0e9'">
                  </el-rate>
                </div>
                <div v-if="item.type == 5" class="textarea">
                  <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请填写答案" v-model="item.answer"></el-input>
                </div>
              </div>
            </div>
            <el-row>
              <!-- <el-button v-if="editType==1 && userType ==4 " @click="" > 提交 </el-button> -->
            </el-row>

          </div>

        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="classRoom.assessment = false">关闭</el-button>
          <!-- <el-button type="primary" >确 定</el-button> -->
        </span>
      </div>
    </el-dialog>

  </div>
</template>
<script lang="ts" setup>
import {defineComponent, nextTick, onBeforeUpdate, reactive, ref, toRefs, watch} from "vue";
//课程详情
import course from "./components/Course.vue";

//课堂评价
import TeacherEvaluation from "./components/TeacherEvaluation.vue";

//学习台
import StudyDesk from "./components/StudyDesk.vue";

import { useRoute, useRouter } from "vue-router";
import listService from "@/service/listService";
import baseService from "@/service/baseService";
import {getCache, setCache} from "@/utils/cache";
import {ElMessage} from "element-plus";
const route = useRoute();
const router = useRouter();
const currentPath = ref(route.path);
watch(
  //监听路由
  () => router.currentRoute.value.path,
  (val) => {
    currentPath.value = val;
    window.clearInterval(timer);
  }
);

//默认选择第一节课时
const studyType = route.query.type;
//取当前用户的登录类型
const userType = getCache('userType', { isSessionStorage: true }, {})
const userInfo = getCache('CacheToken', { isSessionStorage: true }, {})
const classHourIndex = ref(0);
const classRoom = reactive({
      companyEntity: {},
      userInfo: {},
      classRoomEntity: {},
      classRoomFileList: [],
      courseEntity:{},
      classHourList: [],
      onlineStudent: [],
      completedQuestion:0,
      classHourFileList:[],
      hourId:null,
      classRoomId:route.query.id,
      classHour: {},
      assessment: false,
      onlineNum:0,

    }
);

const teacherEvaluation = ref<any>([]);
// 每次更新前把实例清空
// eslint-disable-next-line no-undef
onBeforeUpdate(() => {
  teacherEvaluation.value =[];
});
const setItemRef = (el) => {
  if (el) {
    teacherEvaluation.value.push(el);
  }
};

/**
 * 获取学习台数据
 * 1、获取课堂信息
 * 2、获取课程信息
 * 3、获取课时资料
 * 4、获取在线学生 - 独立方法
 */
const queryClassHour = () => {
  const classRoomId = route.query.id;
  console.log("---", classRoomId);
  baseService
      .post("/fii/front/classRoom/queryClassRoom", {classRoomId: classRoomId})
      .then((res) => {
            if (res.code === 0) {
              classRoom.userInfo = res.data.USER_INFO;
              classRoom.companyEntity = res.data.companyEntity;
              classRoom.classRoomEntity = res.data.classRoomEntity;
              classRoom.classRoomFileList = res.data.classRoomFileList;
              classRoom.courseEntity = res.data.courseEntity;
              classRoom.classHourList = res.data.classHourList;
              if (classRoom.classHourList.length <= 0) {
                return;
              }
              let classHourId = classRoom.classHourList[0].id;

              queryClassHourFile(classHourId);
              classRoom.hourId = classRoom.classHourList[0].id;
              nextTick(() => {
               // teacherEvaluation.value[0].queryQuestion();
              });
            } else {
            }
          }
      );
};

/**
 * 切换课时
 * @param index
 */
const changeClassHour = (index: any, id: number) =>{
  classHourIndex.value = index;
  //查询课时资料
  const classHourList = classRoom.classHourList;
  if(classHourList.length>0){
    let classHourId = classHourList[index].id;
    classRoom.hourId=classRoom.classHourList[index].id;
    queryClassHourFile(classHourId);
  }
}

const topicArray:any = ref({
  title: "评价一",
  status:0,
  creator: "zhangsan",
  create_at: "2022-04-08 10:00:00",
  updator: "zhangsan",
  update_at: "2022-04-08 10:00:00",
  questionList: [
  ],
});

//查看课堂评价
const showAssesment = (item: Object) => {
  if(userType == 3 && item.questionStatus != 0 && item.answerNum > 0){
    classRoom.assessment = true;
    baseService.get("/fii/front/question/queryQuestionAndAnswer?classRoomId="+classRoom.classRoomId+"&userId="+item.userId, {
        })
        .then((res) => {
              if (res.code === 0) {
                topicArray.value = res.data;
                topicArray.value.status = res.data.status;
                topicArray.value.questionList =res.data.questionList;
                console.log(res)
                console.log(topicArray.value.questionList)
              } else {
              }
            }
        );
  }
}

//获取课件
const queryClassHourFile = (classHourId: number) => {
  const classRoomId = route.query.id;
  baseService
      .post("/fii/front/classRoom/queryClassHourFile", {classHourId: classHourId})
      .then((res) => {
            if (res.code === 0) {
              classRoom.classHourFileList = res.data;
              queryClassHourEntity(classHourId);
            }
          }
      );
}

//获取课时详情
const queryClassHourEntity = (classHourId: number) => {
  baseService
      .post("/fii/front/classRoom/queryClassHour", {classHourId: classHourId})
      .then((res) => {
            if (res.code === 0) {
              let result = res.data;

              //视频
              let videos = result.videos;
              let videosUrl = new Array();
              if(videos!=null && videos.length>0){
                let videosArr = videos.split(';');
                for(let i=0;i<videosArr.length;i++) {
                  let urls = videosArr[i].split('@');
                  videosUrl.push(urls.length > 0 ? urls[0] : urls);
                }
              }
              result.videos = videosUrl;

              //课件
              let files = result.files;
              let filesUrl = new Array();
              if(files!=null && files.length>0){
                let filesArr = files.split(';');
                for(let i=0;i<filesArr.length;i++){
                  let urls = filesArr[i].split('@');
                  filesUrl.push(urls.length > 0 ? urls[0] : urls);
                }
              }
              result.files = filesUrl;
              classRoom.classHour = result;
              console.log(classRoom.classHour)
            }
          }
      );
}

//获取课程的所有课时列表
const queryClassHourList = () => {
  const courseId = route.query.id;
  baseService
      .post("/fii/front/classRoom/queryClassHourList", {courseId: courseId})
      .then((res) => {
            if (res.code === 0) {
              classRoom.courseEntity = res.data.courseEntity;
              classRoom.companyEntity = res.data.companyEntity;
              classRoom.userInfo = res.data.userInfo;
              classRoom.classHourList = res.data.classHourList;
              if(classRoom.classHourList.length>0){
                let classHourId = classRoom.classHourList[0].id;
                classRoom.hourId=classRoom.classHourList[0].id;
                queryClassHourFile(classHourId);
              }
            }
          }
      );
}


//退出课堂
const signOutClassRoom = () => {
  const classRoomId = route.query.id;
  baseService
      .post("/fii/front/classRoom/signOut", {classRoomId: classRoomId})
      .then((res) => {
            if (res.code === 0) {
              //后退并刷新
              // router.go(-1);
              if (studyType == '2') {
                router.push({path: '/course/list'});
              }
              if (studyType == '3') {
                router.push({path: '/class_room'});
              }
            }
          }
      );
}


//获取在线学生
const queryOnlineStudent = () => {
  const classRoomId = route.query.id;
  baseService
      .post("/fii/front/classRoom/onlineStudent", {classRoomId: classRoomId})
      .then((res) => {
            if (res.code === 0) {
              classRoom.completedQuestion = 0
              classRoom.onlineNum = 0
              classRoom.onlineStudent = res.data;
              classRoom.onlineStudent.forEach(function(e){
                if(e.answerNum > 0){
                  classRoom.completedQuestion++
                }
                if(e.onlineFlag){
                  classRoom.onlineNum++
                }
              })
            }
          }
      );
}


/**
 * 页面初始化方法调用
 */

if( studyType=='1') {
  queryClassHour();
}

//标准学习台
if( studyType=='1'||studyType=='2') {
  //查询所有课时
  queryClassHourList();
}

//课堂学习台
// 定义定时器
var timer : any = null;
if(studyType=='3'){
  queryClassHour();
  timer = setInterval(function(){
    queryOnlineStudent();
  },3000);
}



</script>


<style lang="scss" scoped>
@import "index.scss";
</style>
